import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from './stores/GlobalStore';
import Vrouter from "@/router";

const service = axios.create({
      baseURL: '/api',
    timeout: 1000 * 180,
    withCredentials: true
  })
 let notLogin=["app/user/login","app/user/register","app/dubRole/dubRoleList","app/user/sendCaptcha"];
 
// 请求拦截器
service.interceptors.request.use(
  config => {
      //设置token
      let token=  store().token;
      if(token!=null&&token!=""){
        config.headers.TOKEN_USER=token;

      }else{
        if(isLogin(config.url)){
          ElMessage({
            message: "请登录后访问",
            center: true,
      
            type: 'error',
            })
            Vrouter.push({path:"/login"});
            return false;
        }
      }

  
    return config;
  },
  error => {
    // 请求错误处理
    console.log(error); // for debug
  }
);
service.interceptors.response.use(response=>{
  let res=response.data;
  if(response.data.code==200){
    //成功
     
     return res.data; 

   }else {
     //失败
     if(res.code=="0001"){
      //后端返回0001代表未登录 直接跳转登录
      Vrouter.push({path:"/login"});
    }
    ElMessage({
      message: res.msg,
      center: true,

      type: 'error',
      })
  
     return Promise.reject(res.msg);
  }
})

function  isLogin(url){
   let is= !notLogin.some(word => url.includes(word));
  return is;
}
 
 
  export default service